package com.woyao;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.woyao.core.FileUtil;
import com.woyao.core.model.Demand;
import com.woyao.core.model.MediaSummary;
import com.woyao.core.util.Common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class DemandMediaActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private  MediaAdapter mediaAdapter;
    private ProgressBar progress;

    private Button recordBtn;
    private Button cameraBtn;
    private Button videoBtn;
    private Button photoBtn;


    List<MediaSummary> data = new ArrayList<MediaSummary>();

    Integer IMAGE_CODE  = 22 ;
    Integer VIDEO_CODE  = 44 ;
    Integer RECORD_CODE =  33;
    Integer CAMERA_CODE =  11;

    private  Demand demand = new Demand();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demand_media);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        Intent intent = getIntent();
        demand = (Demand)intent.getExtras().get("demand");
        data = demand.getMedias();
        setTitle("视频/图片管理");
//
//        for  ( String onepic : demand.getPics() ){
//            MediaSummary ms = new MediaSummary();
//            ms.setIs_main( false);
//            ms.setOrigin( onepic );
//            if (!onepic.endsWith("mp4")) {
//                ms.setUrl(onepic + "?x-oss-process=image/resize,m_fixed,h_60,w_60");
//            }else{
//                ms.setUrl(onepic);
//            }
//            data.add(ms);
//        }

        Button finishBtn = (Button) findViewById(R.id.demand_media_finish);
        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("changed",mediaAdapter.changed);

                demand.setMain_image(mediaAdapter.getMainImage());
                demand.setMedias(mediaAdapter.getMedias());
                intent.putExtra("demand",demand);
                setResult(666, intent);
                finish();
            }
        });

        progress = (ProgressBar)  findViewById(R.id.uploading);
        cameraBtn = (Button) findViewById(R.id.media_camera);

        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });

        videoBtn = (Button) findViewById(R.id.media_add_video);

        videoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               chooseVideo();
            }
        });

        recordBtn = (Button) findViewById(R.id.media_record_video);

        recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass( DemandMediaActivity.this, VideoActivity.class);
                startActivityForResult(intent ,RECORD_CODE);

            }
        });

        photoBtn = (Button) findViewById(R.id.media_add_photo);

        photoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choosePhoto();
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.demand_medias);
//        this.registerForContextMenu(recyclerView);//切换布局
        mediaAdapter = new MediaAdapter(this, demand.getMedias());

//        mediaAdapter.setChangedHandler(new MediaAdapter.Changed() {
//            @Override
//            public void delete(String picUrl) {
//                Common.setDemandAttr(demand.getId(),"image",picUrl,"del");
//            }
//
//            @Override
//            public void setMain(String picUrl) {
//                Common.setDemandAttr(demand.getId(),"main_image",picUrl);
//                Toast.makeText(DemandMediaActivity.this,"设置完成",Toast.LENGTH_SHORT).show();
//            }
//        });
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));//布局管理器
        recyclerView.setAdapter(mediaAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());//使用默认的动画效果

        checkPerm();
    }

//
//    Button playBtn = (Button)findViewById(R.id.demand_play_video);
//        playBtn.setOnClickListener(new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            Intent intent = new Intent();
//            intent.setClass( DemandNewActivity.this, PlayVideoActivity.class);
//            intent.putExtra("path", demand.getImage());
//            startActivity(intent );
//        }
//    });

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 520)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
            } else
            {
                cameraBtn.setEnabled(false);
                videoBtn.setEnabled(false);
                photoBtn.setEnabled(false);
                // Permission Denied
                Toast.makeText(DemandMediaActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void checkPerm() {
        /**1.在AndroidManifest文件中添加需要的权限。
         *
         * 2.检查权限
         *这里涉及到一个API，ContextCompat.checkSelfPermission，
         * 主要用于检测某个权限是否已经被授予，方法返回值为PackageManager.PERMISSION_DENIED
         * 或者PackageManager.PERMISSION_GRANTED。当返回DENIED就需要进行申请授权了。
         * */
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){ //权限没有被授予
            /**3.申请授权
             * @param
             *  @param activity The target activity.（Activity|Fragment、）
             * @param permissions The requested permissions.（权限字符串数组）
             * @param requestCode Application specific request code to match with a result（int型申请码）
             *    reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
             *    int, String[], int[])}.
             * */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    520);
        }else{//权限被授予

        }

    }

    void choosePhoto(){

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/");
        // start the image capture Intent
        startActivityForResult(intent, IMAGE_CODE);
    }

    void chooseVideo(){

        Intent intent = new Intent();
        intent.setType("video/*");
        // start the image capture Intent
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, VIDEO_CODE);
    }

    void takePhoto(){

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CODE);
    }



        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == IMAGE_CODE ){
            try {
                Uri selectedImage = data.getData();
                String localpicpath = Common.getPath(DemandMediaActivity.this,selectedImage);

//                String[] filePathColumn = {MediaStore.Images.Media.DATA};
//                Cursor cursor = getContentResolver().query(
//                        selectedImage, filePathColumn, null, null, null);
//                String picturePath = "";
//                if(cursor!=null) {
//                    cursor.moveToFirst();
//                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                    picturePath = cursor.getString(columnIndex);
//                    cursor.close();
//                }
//                else
//                {
//                    picturePath = selectedImage.getPath();
//                }
                uploadImage( localpicpath, FileUtil.getPicObjectKey());

            }catch(Exception e){
                e.printStackTrace();
            }
        }else if(requestCode == RECORD_CODE ){
            try {
                String videoPath = data.getStringExtra("path");
                uploadVideo(videoPath  , FileUtil.getVideoObjectKey());
            }catch(Exception e){
                e.printStackTrace();
            }
        }else if(requestCode == VIDEO_CODE){
            try {
                Uri selecteds = data.getData();
                // 视频其他信息的查询条件
//                String[] theColumns = new String[] { MediaStore.Video.Media.DATA };
                String thePath = Common.getPath( this,selecteds );

                uploadVideo(  thePath, FileUtil.getVideoObjectKey());

            }catch(Exception e){
                e.printStackTrace();
            }
        }else  if(requestCode == CAMERA_CODE ) {

            Bundle bundle = data.getExtras();
            // 转换图片的二进制流
            Bitmap bitmap = (Bitmap) bundle.get("data");
            // 设置图片
            String filename = FileUtil.getPicObjectKey() +".png";
            String filepath = Common.getDiskCachePath( this)  +"/" + filename;
            Common.compressImage(bitmap,  filepath);
            uploadImage(  filepath,  filename );
        }
    }

    private void addOneMedia( final String filepath ,final String mediaId){


        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mediaAdapter.addMedia(filepath,mediaId);
            }
        });


    }

    private void uploadVideo(  String  videoPathOrigin ,final String filename ){
        progress.setProgress( 10  );
//        String cachepath = Common.getDiskCachePath(this);

//        Common.cutMp4(1, 60*1000, videoPathOrigin, cachepath, filename);

//        final String videoPath  = cachepath + "/" + filename;
        final String videoPath  =   videoPathOrigin;
        TimerTask task = new TimerTask(){
            public void run(){
                progress.setProgress( 40  );
                final File file = new File(videoPath);
                if (file.length() < 1000) {
                    DemandMediaActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Common.alert(DemandMediaActivity.this, "上传失败");
                        }
                    });
                    return;
                }

                OSS oss = FileUtil.getOss(getApplicationContext());
                PutObjectRequest put = new PutObjectRequest(FileUtil.videoBucketName, filename, videoPath);

// 异步上传时可以设置进度回调
                put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                        progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
                    }
                });

                OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                Toast.makeText(DemandMediaActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
                        Common.setDemandAttr(demand.getId(),"image","aliyun"+filename,"add");
                        String videoUrl = "https://woyaooovideo.oss-cn-hangzhou.aliyuncs.com/" + filename;
                        addOneMedia(  videoUrl ,"aliyun"+filename);
                        progress.setProgress(  100  );

                        DemandMediaActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Common.alert(DemandMediaActivity.this,"上传完成。");
                            }
                        });

                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常

                        }

                        DemandMediaActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Common.alert(DemandMediaActivity.this,"上传失败");
                            }
                        });

                    }
                });

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000*3);
        progress.setProgress( 20  );



    }

    private void uploadImage( final String picturePath, final String filename ){
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);


// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Common.setDemandAttr( demand.getId()  ,"image","aliyun"+filename,"add");
                String picUrl = "https://woyaooo1.oss-cn-hangzhou.aliyuncs.com/" + filename;
                addOneMedia( picUrl, "aliyun"+filename );
//                Toast.makeText(DemandMediaActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
                Toast.makeText(DemandMediaActivity.this,"上传失败",Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed",mediaAdapter.changed);
        demand.setMain_image(mediaAdapter.getMainImage());
        demand.setMedias(mediaAdapter.getMedias());
        intent.putExtra("demand",demand);
        setResult(666, intent);
        finish();
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed",mediaAdapter.changed);
            demand.setMain_image(mediaAdapter.getMainImage());
            demand.setMedias(mediaAdapter.getMedias());
            intent.putExtra("demand",demand);

            setResult(666, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}

